#!/bin/bash

# 日志函数
log() {
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

# 获取节点信息
NODE_NAME=$(hostname)
log "开始清理节点: $NODE_NAME"

# 检查是否提供了镜像匹配模式
if [ -n "$IMAGE_PATTERNS" ]; then
  log "使用镜像匹配模式: $IMAGE_PATTERNS"
  # 将逗号分隔的模式保存到文件
  echo "$IMAGE_PATTERNS" | tr ',' '\n' > /tmp/patterns.txt
fi

# 获取所有正在使用的镜像
log "正在获取使用中的镜像..."
CONTAINERS=$(crictl ps -a -q)

# 创建临时文件存储使用中的镜像ID
USED_IMAGES_FILE=$(mktemp)

for CONTAINER in $CONTAINERS; do
  IMAGE_ID=$(crictl inspect --output json $CONTAINER | grep -o '"imageRef": "[^"]*"' | cut -d '"' -f 4)
  echo "$IMAGE_ID" >> $USED_IMAGES_FILE
done

# 获取所有镜像
ALL_IMAGES=$(crictl images -q)

# 清理未使用的镜像
log "开始清理未使用镜像..."
DELETED=0
FAILED=0

for IMAGE in $ALL_IMAGES; do
  # 获取镜像详细信息
  IMAGE_INFO=$(crictl inspecti --output json $IMAGE 2>/dev/null)
  if [ -z "$IMAGE_INFO" ]; then
    log "无法获取镜像信息: $IMAGE, 跳过"
    continue
  fi
  
  # 提取镜像名称
  IMAGE_NAMES=$(echo "$IMAGE_INFO" | grep -o '"repoTags":\[[^]]*\]' | grep -o '"[^"]*"' | grep -v "repoTags" | tr -d '"')
  if [ -z "$IMAGE_NAMES" ]; then
    # 如果没有repoTags，尝试获取repoDigests
    IMAGE_NAMES=$(echo "$IMAGE_INFO" | grep -o '"repoDigests":\[[^]]*\]' | grep -o '"[^"]*"' | grep -v "repoDigests" | tr -d '"')
    if [ -z "$IMAGE_NAMES" ]; then
      IMAGE_NAMES="<none>:<none>"
    fi
  fi
  
  # 检查镜像是否在使用中
  if grep -q "$IMAGE" "$USED_IMAGES_FILE"; then
    log "跳过使用中的镜像: $IMAGE_NAMES"
    continue
  fi
  
  # 检查镜像是否匹配指定模式
  SHOULD_DELETE=false
  if [ -n "$IMAGE_PATTERNS" ]; then
    while IFS= read -r PATTERN; do
      if echo "$IMAGE_NAMES" | grep -q "$PATTERN"; then
        SHOULD_DELETE=true
        break
      fi
    done < /tmp/patterns.txt
  else
    # 如果没有指定模式，则删除所有未使用的镜像
    SHOULD_DELETE=true
  fi
  
  if [ "$SHOULD_DELETE" = "true" ]; then
    log "删除未使用镜像: $IMAGE_NAMES (ID: $IMAGE)"
    if crictl rmi "$IMAGE" 2>/dev/null; then
      DELETED=$((DELETED+1))
    else
      log "删除失败: $IMAGE_NAMES"
      FAILED=$((FAILED+1))
    fi
  else
    log "跳过不匹配模式的镜像: $IMAGE_NAMES"
  fi
done

# 删除临时文件
rm -f $USED_IMAGES_FILE
rm -f /tmp/patterns.txt

# 清理悬空镜像 (如果指定了模式，则跳过悬空镜像清理)
if [ -z "$IMAGE_PATTERNS" ]; then
  log "清理悬空镜像..."
  crictl rmi --prune 2>/dev/null
fi

log "清理完成: 删除 $DELETED 个镜像, 失败 $FAILED 个" 